/**
 * Created by Administrator on 16-9-29.
 */
if (typeof console == "undefined") {    this.console = { log: function (msg) {  } };}
WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
WEB_SOCKET_DEBUG = true;
var ws, name, client_list={};
var nickname;

// 连接服务端
function connect() {
    // 创建websocket
    ws = new WebSocket("ws://192.168.2.116:7272");
    // 当socket连接打开时，输入用户名
    ws.onopen = onopen;
    // 当有消息时根据消息类型显示不同信息
    ws.onmessage = onmessage;
    ws.onclose = function() {
        console.log("连接关闭，定时重连");
        connect();
    };
    ws.onerror = function() {
        console.log("出现错误");
    };
}

// 连接建立时发送登录信息
function onopen()
{
    var HomeUserInfo = $("#HomeUserInfo").val();
        HomeUserInfo = JSON.parse(HomeUserInfo);
    // 登录
    var login_data = '{"type":"login","client_name":"'+(HomeUserInfo.nickname).replace(/"/g, '\\"')+'","room_id":"1","userid":"'+HomeUserInfo.id+'","level":"'+HomeUserInfo.levelid+'","loginlogid":"'+HomeUserInfo.loginlogid+'"}';
    console.log("websocket握手成功，发送登录数据:"+login_data);
    ws.send(login_data);
}

// 服务端发来消息时
function onmessage(e)
{
    console.log(e.data);
    var data = eval("("+e.data+")");
    switch(data['type']){
        // 服务端ping客户端
        case 'ping':
            ws.send('{"type":"pong"}');
            break;
        // 登录 更新用户列表
        case 'login':
            //{"type":"login","client_id":xxx,"client_name":"xxx","client_list":"[...]","time":"xxx"}

            say(data['client_id'], data['client_name'],  data['client_name']+' 加入了书虫聊天室，开心地玩耍吧', data['time']);
            if(data['client_list'])
            {
                client_list = data['client_list'];
            }
            else
            {
                client_list[data['client_id']] = data['client_name'];
            }
            flush_client_list();
            console.log(data['client_name']+"登录成功");
            break;
        // 发言
        case 'say':
            //{"type":"say","from_client_id":xxx,"to_client_id":"all/client_id","content":"xxx","time":"xxx"}
            say(data['from_client_id'], data['from_client_name'], data['content'], data['time']);
            break;
        // 用户退出 更新用户列表
        case 'logout':
            //{"type":"logout","client_id":xxx,"time":"xxx"}
            say(data['from_client_id'], data['from_client_name'], data['from_client_name']+' 退出了', data['time']);
            delete client_list[data['from_client_id']];
            flush_client_list();
    }
}

/**
 * 去除html标记
 *
 * @param  {[type]} str [description]
 * @return {[type]}     [description]
 */
function removeHTMLTag(str)
{
    str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
    str = str.replace(/(^\s*)|(\s*$)/g, "");
    str = str.replace(/(^\s*)/g, "");
    str = str.replace(/(\s*$)/g, "");
    str=str.replace(/&nbsp;/ig,'');//去掉&nbsp;
    return str;
}

function translate(string)
{
    string = string.replace(/&lt;/g ,'<');//将&lt;转成<
    string = string.replace(/&quot;/g,'"');//将&quot;转成"
    string = string.replace(/&gt;/g,'>');//将&gt;转成>
    return string;
}


// 提交对话
function onSubmit() {
    var input = $("#chatText").html();
    if(input.length==0)
    {
        alert('请输入内容');
        return false;
    }
    var to_client_id = 'all';
    var to_client_name = '所有人';
    ws.send('{"type":"say","to_client_id":"'+to_client_id+'","to_client_name":"'+to_client_name+'","content":"'+input.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r')+'"}');
    $("#chatText").html('');
}

// 刷新用户列表框
function flush_client_list(){
    var userlist_window = $("#userList");
    userlist_window.empty();
    userlist_window.append(' <div class="talkRight_list_head bottom_line"> 用户列表</div>');
    for(var p in client_list){
        userlist_window.append('<div class="talkRight_list_head bottom_line user_hover" id="'+p+'"> '+client_list[p]+'</div>');

    }
}

// 发言
function say(from_client_id, from_client_name, content, time){
    //$("#userTalkContent").append('<div class="speech_item"><img src="http://lorempixel.com/38/38/?'+from_client_id+'" class="user_icon" /> '+from_client_name+' <br> '+time+'<div style="clear:both;"></div><p class="triangle-isosceles top">'+content+'</p> </div>');

    content = translate(content);//转换字符串中的标签，让图片可以显示
    var _html = ' <div class="talkRight_head "></div>'
        +'<div class="talkRight_content">'
        +'<div class="talkRight_img">'
        + '<img src="/Public/home/images/default_head3.jpg" width="30px"height="30px"/>'
        +  '<span class="padding">'+from_client_name+'</span>'
        + '<span class="padding">'+time+'</span>'
        + '</div>'
        + '<div style="float: left">'
        +'<span class="talk_span">'+content+'</span>'
        + '</div>'
        +'</div>';
    $("#userTalkContent").append(_html);
    var div = document.getElementById('userTalkContent');
    div.scrollTop = div.scrollHeight;
}

$(function(){
    select_client_id = 'all';
    $("#client_list").change(function(){
        select_client_id = $("#client_list option:selected").attr("value");
    });
});

